import java.util.PriorityQueue;

public class Solution23 {


    static public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode mergeKLists(ListNode[] lists) {
        //将每个链表的没处理的第一个加入到minHeap中。
        PriorityQueue<ListNode> minHeap = new PriorityQueue<>((a, b) -> a.val - b.val);

        //将每个链表的第一个加入到minHeap中
        for (ListNode list : lists) {
            if (list != null) {
                minHeap.offer(list);
            }
        }

        //新建一个链表保存结果
        ListNode head = new ListNode(0);
        ListNode cur = head;

        //循环的条件是堆没有空
        while (!minHeap.isEmpty()) {
            ListNode top = minHeap.poll();

            //把弹出来的值写到链表中
            cur.next = top;
            cur = cur.next;

            //把top.next放入到minHeap中
            if (top.next != null) {
                minHeap.offer(top.next);
            }
        }

        return head.next;
    }
}
